import {getFaceLogin,getLogin,getloginREN} from '../../api/api'
import { NavBar, Button } from 'react-vant'
import React, { useState, useEffect, useRef } from "react"
import { useNavigate } from 'react-router-dom'
import {  Modal } from 'antd';
export default function Renf() {
    let navigate = useNavigate()
    let video = useRef(null)
    let canvas = useRef(null)
    let [imgSrc, setImgSrc] = useState('')
        const [userId, setUserId] = useState('67b529f89288e1d2fcaba48c')//登录ID
    
    const openMedia = () => {
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }
        // 标准的API
        navigator.mediaDevices
            .getUserMedia({
                video: true,
            })
            .then((stream) => {
                // 摄像头开启成功
                console.log("stream", stream);
                if (video.current) { 
                
           
                video.current.srcObject = stream;
                video.current.play().catch(err => console.error("Playback failed: ", err)); 
                }

            })
            .catch((err) => {
                console.log("err", err);
            });
    }
    const closeMedia = () => {
        video.current.srcObject.getTracks()[0].stop();
    }
    const drawMedia = async () => {
        const ctx = canvas.current?.getContext("2d");
        ctx?.clearRect(0, 0, canvas.current.width, canvas.current.height);
        //绘制视频画面
        ctx.drawImage(
            video.current,
            (canvas.current.width - canvas.current.width * (320 / 240)) / 2,
            0,
            canvas.current.width * (320 / 240),
            canvas.current.height
        );
        //图片转base64编码
        const base64 = canvas.current.toDataURL("image/jpeg");
        setImgSrc(base64);
        console.log("base64", base64);

        let { data: { code, msg, data } } = await getFaceLogin({base64: base64.split(',')[1]})
        var msgs=msg
            
        if (code == 200) {
         
            console.log("data", data);
            Modal.info({
                title: '提示',
                content: (
                    <div>
                        <p>{msgs}</p>
                    </div>
                ),
                onOk() {
                    console.log('Confirmed');
                },
            });
            localStorage.setItem('user', JSON.stringify(data))
            let addfrom = { phone: '寻宝之旅', password: '15354131172qwer', seconds: 'Jfur' }
            let { data: { code, msg,} } = await getLogin(addfrom)
            let {data:{token}}=await getloginREN(undefined)
            localStorage.setItem('token', token)
            localStorage.setItem('_id', userId)
            navigate('/home/service')
        } else {
            alert('登录失败')
            navigate('/login')

        }


    }
    useEffect(() => {
        openMedia()
    }, [])
    return (
        <div>
            <NavBar
                title="人脸识别中"
                leftText="返回"
                rightText="按钮"
                onClickLeft={() => {navigate('/')}}
                onClickRight={() => {navigate('/')}}
            />
            {/* <button onClick={closeMedia}>关闭摄像头</button> */}
            {/* <!-- 摄像展示要用video标签 --> */}
            <div style={{ width: '300px', height: '300px', border: '1px solid', marginLeft: '36px', borderRadius: '150px', marginTop: '30px' }}>
                <video ref={video} preload autoplay loop muted width="300" height='300' style={{ borderRadius: '193px' }}></video>
            </div>
            {/* <!-- 截取的照片用canvas标签展示 --> */}
            <div style={{ width: '300px', height: '300px', border: '1px solid', marginLeft: '26px', position: 'relative', top: '-303px', left: '13px' }}>
                <canvas ref={canvas} width="300" height="300"></canvas>
            </div>
            <Button type='primary' block round onClick={drawMedia} style={{ width: '312px', marginLeft: '40px' ,marginTop:'-21rem' }}>
                采集本人人脸
            </Button>
            <Button type='primary' block round onClick={closeMedia} style={{ width: '312px', marginLeft: '40px',marginTop:'1rem' }}>
                关闭摄像头
            </Button>

        </div>
    )
}